USE Lib
GO

---------------------------------------------------------------------------
-- BEGIN MAINTENANCE WRAPPER
----------------------------
IF EXISTS (SELECT * FROM sysobjects WHERE type = 'FN' AND name = 'fn_seek_val') BEGIN
	DROP  FUNCTION  tsql.fn_seek_val
	PRINT '<<< DROP FUNCTION tsql.fn_seek_val - Completed with SUCCESS >>>'
END
GO
----------------------------
-- END MAINTENANCE WRAPPER
---------------------------------------------------------------------------

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


/*================================================================================================
Name:			tsql.fn_seek_val
Type:			User defined function 
Owner:					
Description:	Returns the position of the first occurence of a given value in a coma sepparated list of values 
Parameters:		@list = list of values comma delimited
				@item_value = value to find
Dependens on:  	fn_split
Usage:			SELECT [tsql].[fn_seek_val] ('1,2,2,2,3,4,5','2')
--------------------------------------------------------------------------------------------------
Project:		http://sqllib.codeplex.com/
Help:			http://sqllib.codeplex.com/wikipage?title=fn_seek_val&referringTitle=Documentation		
Version:		20120904
SrcCtrlApp:		SVN
SrcCtrlPath:	http://sqllib.codeplex.com/SourceControl/list/changesets
--------------------------------------------------------------------------------------------------
History:		09/04/2012 - Adrian E Dudau - Function created
================================================================================================*/

CREATE FUNCTION [tsql].[fn_seek_val] (@list NVARCHAR(MAX), @item_value NVARCHAR(4000))
RETURNS BIGINT 
AS

BEGIN
	RETURN(SELECT TOP 1 id FROM (
			SELECT TOP 1 id FROM [tsql].[fn_split](@list,',') 
			WHERE item_value = @item_value
			UNION ALL 
			SELECT id = 0) DTBL
			ORDER BY id DESC 
			)
END

GO

---------------------------------------------------------------------------
-- BEGIN MAINTENANCE WRAPPER
-- Verify completion
----------------------------
IF EXISTS(SELECT * FROM sysobjects WHERE type = 'FN' AND name = 'fn_seek_val') BEGIN 
	PRINT '<<< CREATE FUNCTION tsql.fn_seek_val - Completed with SUCCESS >>>'
END

ELSE BEGIN 
	PRINT '<<< CREATE FUNCTION tsql.fn_seek_val - Completed with ERROR >>>'
END

GO
----------------------------
-- END MAINTENANCE WRAPPER
---------------------------------------------------------------------------


